package com.zx.map.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.*;

import org.joda.time.DateTime;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.modelmapper.spi.MappingContext;

/**
 * Created by bibei on 2016/12/21.
 */
public class MyBeanUtils extends BeanUtils {


	public static final ModelMapper INSTANCE = new ModelMapper();

	static {
		INSTANCE.addConverter(new DateTimeToDateConverter());
		INSTANCE.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
	}

	public static <S, T> T map(S source, Class<T> targetClass) {

		return INSTANCE.map(source, targetClass);
	}

	public static <S, T> void map(S source, T dist) {

		INSTANCE.map(source, dist);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <S, T> List<T> map(List<S> source, Class<T> targetClass) {

		List list = new ArrayList(source.size());
		if(source==null){
			return list;
		}
		for (Object obj : source) {
			Object target = INSTANCE.map(obj, targetClass);
			list.add(target);
		}
		return list;
	}

	public static Map<String, Object> beanToMap(Object source) throws Exception {
		if(source == null){
			throw new Exception("beanToMap source bean is null");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		Field[] fds = source.getClass().getDeclaredFields();
		for(Field f:fds){
			f.setAccessible(true);
			map.put(f.getName(), f.get(source));
		}
		return map;
	}

	/**
	 * 对象转json传
	 * @param object
	 * @return
	 */
	public static String beanToJson(Object object) {
		if (object == null) {
			return "{}";
		}
		return JSON.toJSONString(object);
	}

	/**
	 * 字符串转对象
	 * @param jsonStr
	 * @param targetClass
	 * @param <T>
	 * @return
	 */
	public static <T> T jsonToBean(String jsonStr,Class<T> targetClass) {
		return JSON.parseObject(jsonStr,targetClass);
	}

	/**
	 * 转换成列表
	 * @param jsonStr
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> jsonToListBean(String jsonStr,Class<T> clazz) {
		return JSON.parseArray(jsonStr,clazz);
	}


	private static class DateTimeToDateConverter implements Converter<DateTime, Date> {
		@Override
		public Date convert(MappingContext<DateTime, Date> context) {

			DateTime source = context.getSource();
			if (source != null) {
				return source.toDate();
			}
			return null;
		}
	}
}
